import { computed, reactive, type Ref } from "vue";
import * as journalApi from "@/api/journalApi";
import { ResponseCode } from "@/common/Responsetypes";
import type { IMarkerIconExposedProps } from "@/common/MapTypes";
import { IUploadImgStatus, type IUploadImg } from "@/common/JournalTypes";

interface IJournalInfo {
  content: string;
  photos: { url: string; index: number }[];
  is_open: boolean;
}

export default function (
  fileList: Ref<IUploadImg[]>,
  activeMarkerRef: Ref<null | IMarkerIconExposedProps>
) {
  // true, 所有都上传完了，false，还有没上传完的
  const imgUploadedRef = computed(() => {
    return !fileList.value.some(
      (file) => file.status === IUploadImgStatus.UPLOAD
    );
  });

  const journalInfo: IJournalInfo = reactive({
    content: "",
    photos: [],
    is_open: true,
  });

  async function handlePublishJournal() {
    if (journalInfo.content === "") {
      uni.showToast({
        title: "内容不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    if (!imgUploadedRef.value) {
      uni.showToast({
        title: "图片还未上传完",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    journalInfo.photos = fileList.value.map((file, index) => {
      return {
        url: file.url,
        index,
        min: file.min,
      };
    });

    uni.showLoading();

    const result = await journalApi.add({
      ...journalInfo,
      m_id: activeMarkerRef.value?.poi.m_id,
    });

    if (result.code === ResponseCode.PASS) {
      uni.hideLoading();
      uni.showToast({
        title: "发布成功",
        icon: "success",
        duration: 2000,
        success() {
          setTimeout(() => {
            uni.navigateBack();
          }, 2000);
        },
      });
    }
  }

  return {
    handlePublishJournal,
    journalInfo,
    imgUploadedRef,
  };
}
